package dk.au.transxor.mote;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;

import dk.au.transxor.message.IMessage;
import dk.au.transxor.message.MessageFactory;

import net.tinyos.message.Message;
import net.tinyos.message.MessageListener;

public class ThrottleFileSender extends FileSender implements MessageListener {

	private List<IMessage> messages;
	private int index;
	
	public ThrottleFileSender(int amType, int maxDataLength, MoteUart moteUart,
			int moteId, int sendDelay) throws FileNotFoundException {
		super(amType, maxDataLength, moteUart, moteId, sendDelay);
		
		index = 0;
	}

	@Override
	public void sendFile(File file, boolean waitInput) {
		try {	
			// Read file and make messages
			messages = readFile(file);
	
			if (messages != null) {
				
				BufferedReader consoleInput = new BufferedReader(new InputStreamReader(System.in));
				String input = null;
				
				if(waitInput) {
					System.out.println("Send messages? (s: stop, otherwise: send)");
					input = consoleInput.readLine();
					
					if(input.equals("s")) {
						return;
					}
				}
				
				// Send first message
				moteUart.addMessageListener((Message) MessageFactory.createMessage(amType), this);
				moteUart.sendMessage(moteId, (Message) messages.get(index));
				
				System.out.println(messages.get(index).get_data_seq() + ": " + new String(((IMessage) messages.get(index)).get_data_field()));
				index++;
			}
	
			System.out.println("First message sent!");
		
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

	@Override
	public void messageReceived(int to, Message m) {
		
		if(index < messages.size()) {
			
//			try {
//				Thread.sleep(sendDelay);
//			} catch (InterruptedException e) {
//				e.printStackTrace();
//			}
			
			moteUart.sendMessage(moteId, (Message) messages.get(index));
		
			//System.out.println(messages.get(index).get_data_seq() + ": " + new String(((IMessage) messages.get(index)).get_data_field()));
			index++;
			
		}
		else {
			
			moteUart.removeMessageListener((Message) MessageFactory.createMessage(amType), this);
			System.out.println("FileSender: All messages have been sent!");
			
		}
	}
}
